<template>
  <div>
    <page-view class="food-detail-page">
      <page-header title="菜单详情" :show-back="true"></page-header>
      <!-- 内容：图片+详细信息 -->
      <div class="content-box" v-if="foodDetail">
        <skeleton title avatar :row="3" :loading="loading">
          <!-- 菜单图片展示 -->
          <div class="food-img-box">
            <img
              v-lazy="BaseURL + foodDetail.food_img"
              @click="showThisImage"
            />
          </div>
          <!-- 详情展示 -->
          <ul class="food-desc">
            <li>
              <span>菜单名称：{{ foodDetail.food_name }}</span>
            </li>
            <li>
              <span>菜单价格：{{ foodDetail.price }}</span>
            </li>
            <li>
              <span>菜单重量：{{ foodDetail.weight }}</span>
            </li>
            <li class="food-intro">{{ foodDetail.food_desc }}</li>
          </ul>
          <!-- 留言展示 -->
          <div class="comment-list">
            <h3 class="text-primary">最新评论</h3>
            <pull-refresh v-model="refreshing" @refresh="onRefresh">
              <list
                v-model:loading="loading"
                :finished="finished"
                finished-text="留言全部加载完了。。。"
                @load="onLoad"
              >
                <comment-item
                  v-for="item in commentList"
                  :key="item.id"
                  :c_item="item"
                ></comment-item>
                {{ commentList }}
              </list>
            </pull-refresh>
          </div>

          <!-- 购物车ActionBar组件 -->
          <action-bar>
            <action-bar-icon icon="chat-o" text="客服" dot />
            <action-bar-icon
              icon="cart-o"
              text="购物车"
              :badge="shopCarBarData.totalCount"
            />
            <action-bar-button
              type="warning"
              text="加入购物车"
              @click="addToShopCar"
              :loading="shopCarButtonLoading"
            />
            <!-- 跳转到购物车页面 -->
            <action-bar-button
              type="danger"
              text="立即购买"
              @click="$router.push({ name: 'ShopCart' })"
            />
          </action-bar>
        </skeleton>
      </div>
    </page-view>
  </div>
</template>

<script>
//获取 路由
import { useRoute, useRouter } from "vue-router";
//获取 仓库
import { useStore } from "vuex";
import CommentItem from "../components/CommentItem.vue";
import { onMounted, reactive, toRefs, getCurrentInstance, ref } from "vue";
import Api from "../utils/api";
import {
  ImagePreview,
  Skeleton,
  List,
  PullRefresh,
  ActionBar,
  ActionBarIcon,
  ActionBarButton,
} from "vant";
export default {
  name: "FoodDetail",
  components: {
    Skeleton,
    ImagePreview,
    List,
    PullRefresh,
    CommentItem,
    ActionBar,
    ActionBarIcon,
    ActionBarButton,
  },
  setup() {
    //路由 一般用于 获取参数
    const route = useRoute();
    //路由器 一般用于 编程式路由跳转
    const router = useRouter();
    const store = useStore();
    const { proxy } = getCurrentInstance();

    let info = reactive({
      foodDetail: {},
      loading: false,

      commentList: [],
      pageCount: 0,
      pageEnd: 0,
      pageIndex: 1,
      pageStart: 0,
      totalCount: 0,
      finished: false,
      refreshing: false,
    });

    const getFoodDetailById = async (id) => {
      //获取数据前 处于加载状态
      info.loading = true;
      let results = await Api.foodInfo.findById(id);
      console.log("菜品详情", results);
      //获取完数据后 加载状态为false
      info.loading = false;
      info.foodDetail = results;
    };

    //处理留言、评论信息
    const getCommentList = async (fid, pageIndex = 1) => {
      info.loading = true;
      info.finished = false;
      info.refreshing = true;
      let results = await Api.commentInfo.getCommentInfoListById({
        fid,
        pageIndex,
      });
      console.log("留言、评论信息", results);
      info.pageCount = results.pageCount;
      info.pageEnd = results.pageEnd;
      info.pageIndex = +results.pageIndex;
      info.pageStart = results.pageStart;
      info.totalCount = results.totalCount;
      //这里不能够直接赋值，不然是 数组的浅拷贝 最好要是数组的深拷贝
      info.commentList.push(...results.listData);
      info.loading = false;
      info.finished = info.pageIndex >= info.pageCount;
      info.refreshing = false;
    };

    //下滚懒加载评论
    const onLoad = () => {
      if (info.pageIndex < info.pageCount) {
        getCommentList(route.query.fid, info.pageIndex + 1);
      }
    };

    //下拉刷新菜单
    const onRefresh = () => {
      info.finished = false;
      info.refreshing = true;
      info.commentList.length = 0;
      getCommentList(route.query.fid);
    };

    //拿到路由跳转时，携带的query 商品id
    // store.query

    function showThisImage() {
      ImagePreview([proxy.BaseURL + info.foodDetail.food_img]);
    }

    //购物车
    const shopCarBarData = reactive({
      totalCount: 0,
      totalPrice: 0,
    });
    const getMyShopCartTotalInfo = async () => {
      //不是要token吗，不要token也能获取到数据
      let results = await Api.shopCart.getMyShopCartTotalInfo();
      shopCarBarData.totalCount = results.totalCount;
      shopCarBarData.totalPrice = results.totalPrice;
    };

    //要进入购物车模块 必须先登录
    //加入购物车按钮的 加载状态
    let shopCarButtonLoading = ref(false);
    const addToShopCar = () => {
      //看仓库中是否有 userInfo用户信息 以及token
      let userInfo = store.state.userInfo;
      if (userInfo) {
        shopCarButtonLoading.value = true;
        //模拟延时,真正地发起网络请求，向后台存数据
        setTimeout(async () => {
          let results = await Api.shopCart.addToShopCart({
            fid: info.foodDetail.id,
            count: 1,
          });
          proxy.$toast.success("添加成功");
          shopCarButtonLoading.value = false;
          getMyShopCartTotalInfo();
        });
      } else {
        //没有userInfo代表 还没有登录
        proxy.$toast("你还没有登录，请去登录");
        router.push({ name: "Login" }).catch((err) => {
          console.log(err);
        });
      }
    };
    onMounted(() => {
      let fid = route.query.fid;
      getFoodDetailById(fid);
      getCommentList(fid);
      getMyShopCartTotalInfo();
    });

    return {
      onMounted,
      getFoodDetailById,
      ...toRefs(info),
      showThisImage,
      getCommentList,
      onLoad,
      onRefresh,
      shopCarButtonLoading,
      addToShopCar,
      shopCarBarData,
    };
  },
};
</script>

<style lang="scss" scoped>
.food-detail-page {
  @include flexbox(column);
  .content-box {
    flex: 1;
    overflow: auto;
    padding-bottom: 50px;
    .food-img-box {
      height: 250px;
      position: relative;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .food-desc {
      box-sizing: border-box;
      padding: 5px;
      font-size: 14px;
      border-bottom: 1px solid lightgray;
      li {
        line-height: 1.8;
        span {
          font-weight: bold;
        }
        &.food-intro {
          text-indent: 2em;
        }
      }
    }
  }
}
</style>
